#include <iostream>
#include <pthread.h>
#include <string>
#include <vector>
#include <unistd.h>
#include "cond.hpp"
#include "mutex.hpp"
using namespace CondModule;
using namespace MutexModule;

#if 0
// V2
int cnt = 0;
Cond c;
Mutex lock;
void *ThreadRun(void *args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        /* 加锁 */
        lock.Lock();
        /* 等待 */
        c.Wait(lock.GetMutex());
        std::cout << name << " 计算: " << cnt << std::endl;
        cnt++;
        /* 解锁 */
        lock.Unlock();
    }
}


int main()
{
    /* 创建5个线程 */
    std::vector<pthread_t> pthreads;
    for(int i = 1; i <= 5; ++i)
    {
        pthread_t tid;
        char name[64];
        snprintf(name, sizeof(name), "Thread-%d", i);
        int n = pthread_create(&tid, nullptr, ThreadRun, name);
        if(n != 0)
            continue;
        pthreads.push_back(tid);
        sleep(1);
    }

    /* 每隔1s唤醒线程 */
    while(true)
    {
        std::cout << "我要开始唤醒线程了....." << std::endl;
        /* 唤醒一个 */
        // c.Signal();
        /* 唤醒全部 */
        c.Broadcast();
        sleep(1);
    }

    /* 回收线程 */
    for(auto& pthread : pthreads)
    {
        pthread_join(pthread, nullptr);
    }

    return 0;
}
#endif


#if 0
// V1
/* 定义全局锁/全局条件变量 */
pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
int cnt = 0;

void *ThreadRun(void *args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        /* 加锁 */
        pthread_mutex_lock(&glock);
        /* 等待 */
        pthread_cond_wait(&gcond, &glock);
        std::cout << name << " 计算: " << cnt << std::endl;
        cnt++;
        /* 解锁 */
        pthread_mutex_unlock(&glock);
    }
}


int main()
{
    /* 创建5个线程 */
    std::vector<pthread_t> pthreads;
    for(int i = 1; i <= 5; ++i)
    {
        pthread_t tid;
        char name[64];
        snprintf(name, sizeof(name), "Thread-%d", i);
        int n = pthread_create(&tid, nullptr, ThreadRun, name);
        if(n != 0)
            continue;
        pthreads.push_back(tid);
        sleep(1);
    }

    /* 每隔1s唤醒线程 */
    while(true)
    {
        std::cout << "我要开始唤醒线程了....." << std::endl;
        /* 唤醒一个 */
        pthread_cond_signal(&gcond);
        /* 唤醒全部 */
        // pthread_cond_broadcast(&gcond);
        sleep(1);
    }

    /* 回收线程 */
    for(auto& pthread : pthreads)
    {
        pthread_join(pthread, nullptr);
    }

    return 0;
}
#endif